<template>
  <div class="form-select">
    <div class="select-all">
      <a-checkbox
        :indeterminate="indeterminate"
        :checked="checkAll"
        @change="onCheckAllChange"
      >
        全选
      </a-checkbox>
    </div>
    <a-checkbox-group
      v-model="formData[name]"
      :options="options"
      :disabled="disabled"
      @change="onChange"
    >
      <a-checkbox v-for="item in options" :key="item.value" :value="item.value">
        {{ item.label }}
      </a-checkbox>
    </a-checkbox-group>
  </div>
</template>
<script lang="ts">
/**
 *
 */
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'

@Component
export default class CheckboxGroup extends Vue {
  @Prop() name!: any // key
  @Prop({ type: Boolean, default: false }) disabled!: boolean // key
  @Prop({ type: Object, default: () => ({}) }) formData!: { [key: string]: any }
  @Prop({ type: Array, default: () => [] }) options!: any[]

  public indeterminate: boolean = false
  public checkAll: boolean = false

  public mounted() {
    const { formData, name } = this
    this.onChange(formData[name])
  }

  @Watch('formData', { deep: true })
  public watchFormData() {
    const { formData, name } = this
    this.onChange(formData[name])
  }

  public onChange(checkedList: any[]) {
    if (checkedList) {
      this.indeterminate =
        checkedList.length > 0 && checkedList.length < this.options.length
      this.checkAll = checkedList.length === this.options.length
      this.$nextTick(() => {
        this.$emit('change', checkedList)
      })
    }
  }

  // 全选
  public onCheckAllChange($event: any) {
    Object.assign(this, {
      indeterminate: false,
      checkAll: $event.target.checked,
    })
    const checkedList: any = $event.target.checked
      ? this.options.map((item: any) => item.value)
      : []
    this.$emit('select-all', checkedList)
  }
}
</script>
<style lang="less" scoped>
.form-select {
  background: #f1f1f1;
  border-radius: 4px;
  padding: 8px;
  width: 100%;

  .select-all {
    height: 26px;
    line-height: 26px;
  }

  /deep/.ant-checkbox-group-item {
    height: 26px;
    line-height: 26px;
  }
}
</style>
